package com.wms.wms.controller.product;

import com.wms.wms.entity.Result;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Chl
 * @version 1.0
 * @date 2019/12/7 10:44
 */
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result jsonException(Exception e){
        return new Result(false,"数据格式不对");
    }

    @ExceptionHandler
    public Result formatException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        return new Result(false, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler
    public Result handleException(Exception e){
        System.out.println(e.getClass());
        return new Result(false,e.getMessage());
    }

    @ExceptionHandler(MyBatisSystemException.class)
    public void notLogin(HttpServletResponse response) throws IOException {
        response.sendRedirect("/admin/");
    }

}
